/*—————————————————————————————————————————————————————————— 登录页面 ——————————————————————————————————————————————————————————*/

// 数据+css引入
import React, { useEffect, useRef, useState } from 'react'
import { loginFormHead, formItems } from './data'
import './login.scss'

// 公共方法
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import {
  setToken,
  setLongTimeUser,
  removeTimeUser,
  getLongTimeUser,
} from '@/utils/userMessage' // 设置内存数据
import { hashPassword } from '@/utils' // 进行加密
import { longTimeUserInfo } from '@/utils/interface' // 公共接口
import config from '@/common/config/config' // 引入项目的公共配置

// 结构出需要的内容，方便后续操作
const {
  projectName,
  projectIcon,
  projectIntroduce,
  projectHeaderTitles,
  projectVersion,
  projectUpdateTime,
} = config

// 路由hooks引入
// --------------------------------------------------------------------------------------------------------
import { useNavigate } from 'react-router-dom'

// redux引入
// --------------------------------------------------------------------------------------------------------
import { useAppDispatch } from '@/utils/hooks' // redux方法执行
import { updataRouter, setUserMenu } from '@/common/publicStore/reducer' // redux中同步action方法
import { UserMsg } from './interface'

// 组件引入
// --------------------------------------------------------------------------------------------------------
import Pages from '@/components/pagesBox/pages' // 页面公共组件
import { Button, App } from 'antd'
import { HappyProvider } from '@ant-design/happy-work-theme'
import Form from '@/components/form/form'

// ts接口引入
// --------------------------------------------------------------------------------------------------------
import type { FormRef } from '@/components/form/form'
import { IRoute } from '@/router/interface'

// 页面书写区
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
const Login: React.FC<unknown> = () => {
  // 变量声明区
  // ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
  // ref声明
  const formRef = useRef<FormRef>(null) // 获取到当前form组件的Ref，并进行结构重新命名

  // 状态声明
  // -----------------------------------------------------------------------------------------------------------
  const dispatch = useAppDispatch() // 注册修改数据方法
  const navigate = useNavigate() // 路由操作方法
  const { message } = App.useApp() // 使用app组件方法
  const [bntLoading, setBntLoading] = useState<boolean>(false) // 按键登录状态

  // 函数使用区
  // ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
  // hook函数
  // -----------------------------------------------------------------------------------------------------------
  useEffect(() => {
    // 判断当前是否有长期存储的用户信息
    const userMsg = getLongTimeUser()

    // 如果有则进行同步表单的初始化数据
    if (!!userMsg as boolean) {
      const { name, password } = userMsg as longTimeUserInfo

      // 动态修改当前表单内容
      formRef.current.form.setFieldsValue({ name, password, remember: true })
    }
  }, [])

  // 事件函数
  // -----------------------------------------------------------------------------------------------------------
  // 参考版本按键
  const viewVersion = () => {
    message.success('当前是最新版本！')
  }

  // 表单验证出错函数
  // =========================================================================================
  const formErr = () => {
    message.open({
      type: 'error',
      content: '用户名或密码错误！请重新输入！',
    })

    // 关闭按键loading
    setBntLoading(false)
  }

  // 表单验证通过后去登录
  // =========================================================================================
  async function goLogin(value: UserMsg) {
    // 结构出输入的用户名与密码
    const { name, password } = value

    // 如果开启了记住密码
    if (value.remember) {
      // 存入当前设置的用户信息
      setLongTimeUser({ name, password })
    } else {
      // 否则清理当前的用户信息
      removeTimeUser()
    }

    // 加密用户密码
    const hash = await hashPassword(password)

    // 调用登陆接口
    // 设置当前的用户token
    setToken('222')

    console.log(hash)

    // 假设的动态添加路由
    const routerList: IRoute[] = [
      {
        path: '/user',
        index: true,
        isLayOut: ['headr', 'footer', 'sider'],
        fileAddress: '/index/index',
        title: '用户信息',
        name: 'user',
      },
    ]

    dispatch(updataRouter(routerList))
    dispatch(setUserMenu([]))

    // 关闭按键loading
    setBntLoading(false)

    // 跳转至首页
    navigate('/index', { replace: true })
  }

  // dom元素区域
  // ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
  return (
    <Pages className="flexJC Login">
      {/* 头部栏 */}
      <ul className="flexBetween Login-top">
        <li className="flexAIC userNoSelect Login-top-one">
          <i
            className="bgImg"
            style={{ backgroundImage: `url(${projectIcon})` }}
          />{' '}
          {projectName}
        </li>

        <li className="flexBetween userNoSelect Login-top-two">
          <div className="flexAIC userNoSelect">
            <i className="bgImg" /> {projectHeaderTitles[0]}
          </div>

          <div className="flexAIC userNoSelect">{projectHeaderTitles[1]}</div>

          <div className="flexAIC userNoSelect">
            <i className="bgImg" /> {projectHeaderTitles[2]}
          </div>

          <div className="flexAIC userNoSelect">
            <i className="bgImg" /> {projectHeaderTitles[3]}
          </div>
        </li>

        <Button shape="round" onClick={viewVersion}>
          查看版本
        </Button>
      </ul>

      {/* 底层背景 */}
      {/* ----------------------------------------------------------------------------------------------------------- */}
      <div className="flexJC Login-background">
        {/* 内容 */}
        <ul className="userNoSelect Login-background-top">
          <li>Welcome!</li>
          <li>{projectIntroduce}</li>
        </ul>
      </div>

      {/* 登陆表单 */}
      {/* ----------------------------------------------------------------------------------------------------------- */}
      <Form
        className="Login-form"
        name="login"
        labelCol={{ span: 24 }}
        row={{ gutter: [0, 0] }}
        ref={formRef}
        requiredMark={false}
        layout="vertical"
        showFoundationBtn={false}
        formitemlist={formItems}
        slotTop={loginFormHead}
        onFinish={goLogin}
        onFinishFailed={formErr}
        slotDown={
          <HappyProvider>
            <Button
              type="primary"
              shape="round"
              htmlType="submit"
              block
              loading={bntLoading}
              onClick={() => {
                // 开启loading状态
                setBntLoading(true)
              }}
            >
              {bntLoading ? '登 录 中...' : '登 录'}
            </Button>
          </HappyProvider>
        }
      />

      {/* 末尾版本信息 */}
      {/* ----------------------------------------------------------------------------------------------------------- */}
      <div className="Login-version">
        V{projectVersion}
        <span>{projectUpdateTime}</span>
      </div>
    </Pages>
  )
}

export default Login
